package io.gitee.kotle.player.session.impl.exoplayer

import android.app.PendingIntent
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.util.EventLogger
import androidx.media3.session.MediaLibraryService
import androidx.media3.session.MediaSession
import io.gitee.kotle.player.core.createExoPlayer

/**
 *
 * 描述：通知栏服务
 *
 * <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
 * <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
 *
 *  <service
 *    android:name=".MediaService"
 *    android:exported="true"
 *    android:foregroundServiceType="mediaPlayback"
 *    android:permission="android.permission.FOREGROUND_SERVICE">
 *      <intent-filter>
 *         <action android:name="androidx.media3.session.MediaSessionService" />
 *         <action android:name="androidx.media3.session.MediaLibraryService" />
 *         <action android:name="android.media.browse.MediaBrowserService" />
 *      </intent-filter>
 *   </service>
 *
 * @author Jiale.Wei
 *
 * 创建时间：2023/5/5 13:50
 *
 */
abstract class ExoPlayerMediaService : MediaLibraryService(),
    MediaLibraryService.MediaLibrarySession.Callback {
    /**
     * 播放器
     */
    val player by lazy { onCreatePlayer().also {
        it.addAnalyticsListener(EventLogger("===="))
    } }

    /**
     * 创建播放器
     */
    open fun onCreatePlayer(): ExoPlayer {
        return createExoPlayer(this)
    }

    /**
     * MediaLibrarySession
     */
    val mediaLibrarySession by lazy {
        onCreateMediaLibrarySession(onCreateActivityPendingIntent())
    }

    /**
     * 创建MediaLibrarySession
     */
    open fun onCreateMediaLibrarySession(pendingIntent: PendingIntent?): MediaLibrarySession {
        val build = MediaLibrarySession.Builder(this, player, this)
        if (pendingIntent != null) {
            build.setSessionActivity(pendingIntent)
        }
        return build.build()
    }

    /**
     * 创建点击通知栏的意图
     */
    open fun onCreateActivityPendingIntent(): PendingIntent? {
        return null
    }

    override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaLibrarySession? {
        return mediaLibrarySession
    }


    override fun onDestroy() {
        player.release()
        mediaLibrarySession.release()
        super.onDestroy()
    }
}